<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="因子（维度）名称:" prop="factorName" label-width="9rem">
        <el-input
          v-model="queryParams.factorName"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="测评量表:" prop="scaleTitle" label-width="6rem">
        <el-input
          v-model="queryParams.scaleTitle"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="因子分计算公式:" prop="scaleFormula.formulaName" label-width="8.5rem">
        <!-- <el-input
          v-model="queryParams.scaleFormula.formulaName"
          placeholder="请输入因子分计算公式"
          clearable
          @keyup.enter.native="handleQuery"
        /> -->
        <!-- 查询外部的 -->
        <el-select v-model="queryParams.formulaName" 
          @keyup.enter.native="handleQuery" 
          @change="handleFormulaId"
          clearable
          @clear="handleClear">
            <el-option v-for="(item) in formulaList" 
            :label="item.formulaName" 
            :value="item.formulaName"
            :key="item.formulaName"
            ></el-option>
          </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:factor:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:factor:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:factor:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:factor:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="factorList" @selection-change="handleSelectionChange" tooltip-effect="dark myTooltips">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="序号" align="center" prop="factorId" width="90px"/> -->
      <el-table-column label="因子（维度）名称" align="center" prop="factorName"  width="260px"/>

      <el-table-column label="分数范围及结果解释" prop="factorResult" align="center" width="430px"  :show-overflow-tooltip=true>
      </el-table-column>
      
      <el-table-column label="因子分计算公式" align="center" prop="scaleFormula.formulaName" />
      <el-table-column label="所属量表" align="center" prop="scaleTitle" width="350px"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:factor:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:factor:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      v-show="total>0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :total="total">
    </el-pagination>
    <!-- <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @current-change="handleCurrentChange"
    /> -->

    <!-- 添加或修改测评因子信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60rem" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="10rem">
        <el-form-item label="因子（维度）名称:" prop="factorName">
          <el-input v-model="form.factorName" clearable style="width: 17rem;"/>
        </el-form-item>
        <el-form-item label="因子（维度）所属量表:" prop="scaleTitle" >
            <el-select v-model="form.scaleTitle" 
              style="width: 17rem;" 
              @change="handleScaleId" clearable>
              <el-option v-for="(item2,idx2) in scaleTitleList" 
              :label="item2.scaleTitle" 
              :value="item2.scaleTitle"
              :key="idx2"
              ></el-option>
            </el-select>
        </el-form-item>

        <!-- 接口不对，应换接口 -->
        <el-form-item label="量表的总分计分公式:">
          <!-- <el-input v-model="form.scaleFormula.formulaName" placeholder="请输入测评量表标题" /> -->
          <el-select v-model="form.formulaName" 
            style="width: 17rem;"
            @change="handleFormulaId"
            clearable>
            <el-option v-for="(item1,idx1) in formulaList" 
            :label="item1.formulaName" 
            :value="item1.formulaName"
            :key="idx1"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- <el-form-item label="分数范围及结果解释:" prop="factorResult" label-width="7rem">
          <el-input class="factor-input" v-model="form.factorResult" type="textarea"  :autosize="{ minRows: 4, maxRows: 8}" style="width: 17rem;"/>
        </el-form-item> -->

        <el-divider content-position="center">分数范围及结果解释：</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddFactorScale">增加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteFactorScale">删除</el-button>
          </el-col>
        </el-row>
        <!-- 分数范围及结果解释 -->
        <el-table :data="factorResultList" :row-class-name="rowefactorResultIndex"
          @selection-change="handleFactorResultSelectionChange"  tooltip-effect="dark myTooltips">
          <el-table-column type="selection"  align="center"  />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          
          <el-table-column label="分数范围1" prop="ScoreScale1" align="center" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ScoreScale1" />
            </template>
          </el-table-column>
          <el-table-column label="分数范围2" prop="ScoreScale2" align="center" width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.ScoreScale2" />
            </template>
          </el-table-column>
          <el-table-column label="结果提示" prop="Result" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.Result" />
            </template>
          </el-table-column>
          <el-table-column label="心理建议" prop="Heart" align="center">
            <template slot-scope="scope">
              <el-input v-model="scope.row.Heart" />
            </template>
          </el-table-column>
        </el-table>
        
        
        <el-divider content-position="center">预警分数范围及预警级别：</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddscoreResult">增加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeletescoreResult">删除</el-button>
          </el-col>
        </el-row>
        <!-- 预警分数范围 -->
        <el-table :data="scoreResultList" :row-class-name="rowescoreResultIndex"
          @selection-change="handlescoreResultSelectionChange"  tooltip-effect="dark myTooltips">
          <el-table-column type="selection"  align="center"  />
          <el-table-column label="序号" align="center" prop="index" width="60"/>
          
          <el-table-column label="分数1" prop="Score1" align="center" width="75">
            <template slot-scope="scope">
              <el-input v-model="scope.row.Score1" />
            </template>
          </el-table-column>
          <el-table-column label="分数2" prop="Score2" align="center" width="75">
            <template slot-scope="scope">
              <el-input v-model="scope.row.Score2" />
            </template>
          </el-table-column>
          <el-table-column label="年纪范围1" prop="Age1" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.Age1" @change="handleChange" size="mini" style="width:70;"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="年纪范围2" prop="Age2" align="center">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.Age2" @change="handleChange" size="mini" style="width:70;"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="性别" prop="Sex" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.Sex">
                <el-option label="女" value="0" />
                <el-option label="男" value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="预警级别" prop="Level" align="center">
            <template slot-scope="scope">
              <el-select v-model="scope.row.Level" placeholder="请选择" clearable>
                <el-option v-for="dict in dict.type.sys_dangous_level" 
                  :key="dict.value" 
                  :label="dict.label"
                  :value="dict.value">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFactor, getFactor, delFactor, addFactor, updateFactor } from "@/api/system/factor";
import { listFormula } from "@/api/mentalTest/formula.js";
import { listScale } from "@/api/mentalTest/scaleManage";

export default {
  name: "Factor",
  dicts: ['sys_dangous_level'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测评因子信息表格数据
      factorList: [],
      //因子分计算公式
      formulaList: [],
      //所属测评量表标题数据
      scaleTitleList: [],
      //分数范围及结果解释
      factorResultList: [],  
      //预警分数范围及结果解释
      scoreResultList: [],  
      // 子表选中数据
      checkedFactorResult: [],   
      // 预警子表选中数据
      checkedscoreResult: [],   
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        factorName: null,
        scaleId: null,
        scaleTitle: null,
        formulaId: null,
        formulaName:null,
        scaleFormula:{
          formulaId:null,
          formulaName:"",
        },
      },
      // 表单参数
      form: {
        scaleFormula:{
          formulaId:null,
          formulaName:"",
        },
        factorResult:"",
        scoreResult:"",
        factorName: "",
        scaleId: "",
        scaleTitle: "",
        formulaId: "",
        formulaName:"",
      },
      // 表单校验
      rules: {
      },
      routerScaleTitle:''
    };
  },
  created() {
    this.getRouterQuery()
    // this.getList1();
  },
  mounted() {
    this.getList();
    this.getFormula();
  },
  methods: {
    //获取路由参数
    getRouterQuery() {
      this.queryParams.scaleTitle = this.$router.history.current.query.scaleTitle

    },
    /** 查询因子分计算公式列表 */
    getFormula() {
      this.loading = true;
      listFormula({
        formulaId:null,
        formulaName:null,
      }).then(response =>{
        this.formulaList = response.rows;
      })
    },
    //从questionInfo得到所有所属测评量表的标题
    getTitle() {
      // this.queryParams.scaleTitle = '所有';
      listScale(this.queryTitle).then(response =>{
        this.scaleTitleList = response.rows;
      })
    },
    // 分页器页码改变事件
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
        // this.queryParams.pageNum = val
        console.log(`当前页: ${this.queryParams.pageNum}`);
        listFactor({
          pageNum: val,
          pageSize: 10,
          factorName: null,
          scaleId: null,
          scaleTitle: null,
          formulaId: null,
          formulaName:null,
          scaleFormula:{
            formulaName:"",
          },
        }).then(response => {
          this.factorList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log('res',this.factorList)
        });
      },
     //添加问题中的得分控件
    handleChange(value) {
        console.log(value);
    },
    /** 查询测评因子信息列表 */
    getList() {
      this.loading = true;
      listFactor(this.queryParams).then(response => {
        this.factorList = response.rows;
        this.total = response.total;
        this.loading = false;
        console.log('res',this.factorList);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.factorResultList = [],
      this.scoreResultList = [],
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        factorName: null,
        scaleId: null,
        scaleTitle: null,
        formulaId: null,
        formulaName:null,
        scaleFormula:{
          formulaName:"",
        },
      },
      this.form = {
        factorId: null,
        scaleFormula:{
          formulaName:"",
        },
        scaleId: null,
        factorResult: null,
        scoreResult:null,
        scaleTitle: null,
        formulaId: null,
        formulaName:null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reset();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.factorId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getTitle();
      this.open = true;
      this.title = "添加测评因子信息(维度)";
    },
    /** 分数及结果的信息序号 */
    rowefactorResultIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 预警分数及结果的信息序号 */
    rowescoreResultIndex({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    /** 分数及结果的信息添加按钮操作 */
    handleAddFactorScale() {
      let obj = {}
      obj.ScoreScale1 = ""
      obj.ScoreScale2 = ""
      obj.Result = ""
      obj.Heart = ""
      this.factorResultList.push(obj)
    },
     /** 分数及结果的信息删除按钮操作 */
    handleDeleteFactorScale() {
      if (this.checkedFactorResult.length == 0) {
        this.$modal.msgError("请先选择要删除的问题树信息数据");
      } else {
        const factorResultList = this.factorResultList;
        const checkedFactorResult = this.checkedFactorResult;
        this.factorResultList = factorResultList.filter(function (item) {
          return checkedFactorResult.indexOf(item.index) == -1
        });
      }
    },
    
    /** 分数及结果的信息添加按钮操作 */
    handleAddscoreResult() {
      let obj = {}
      obj.Score1 = ""
      obj.Score2 = ""
      obj.Sex = ""
      obj.Age1 = ""
      obj.Age2 = ""
      obj.Level = ""
      this.scoreResultList.push(obj)
    },
     /** 分数及结果的信息删除按钮操作 */
    handleDeletescoreResult() {
      if (this.checkedscoreResult.length == 0) {
        this.$modal.msgError("请先选择要删除的问题树信息数据");
      } else {
        const scoreResultList = this.scoreResultList;
        const checkedscoreResult = this.checkedscoreResult;
        this.scoreResultList = scoreResultList.filter(function (item) {
          return checkedscoreResult.indexOf(item.index) == -1
        });
      }
    },
    /** 复选框选中数据 */
    handleFactorResultSelectionChange(selection) {
      this.checkedFactorResult = selection.map(item => item.index)
    },
    /** 预警复选框选中数据 */
    handlescoreResultSelectionChange(selection) {
      this.checkedscoreResult = selection.map(item => item.index)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const factorId = row.factorId || this.ids
      getFactor(factorId).then(response => {
        this.form = response.data;
        console.log("formulaName",this.form.scaleFormula.formulaName);
        this.form.formulaName = this.form.scaleFormula.formulaName;
        this.getTitle();
        //解析分数范围
        const factorResultArray = this.form.factorResult.split('$%^&');
        this.factorResultList = factorResultArray.map(line => {
          const [scoreScales, jieguo] = line.split('@#$%');
          const [scoreScale1, scoreScale2] = scoreScales.split('!@#$');
          const [result, heart] = jieguo.split('#$%^');
          return {
            ScoreScale1: scoreScale1,
            ScoreScale2: scoreScale2,
            Result: result,
            Heart:heart,
          };
        });
        //解析预警分数
        const scoreResultArray = this.form.scoreResult.split('$%^&');
        this.scoreResultList = scoreResultArray.map(line => {
          const [scoreScales, jieguo] = line.split('@#$%');
          const [score1, score2] = scoreScales.split('!@#$');
          const [sex, al] = jieguo.split('#$%^');
          const [age, level] = al.split('^&*(');
          const [age1, age2] = age.split('%^&*');
          return {
            Score1: score1,
            Score2: score2,
            Sex: sex,
            Age1: age1,
            Age2: age2,
            Level: level,
          };
        });
        this.open = true;
        this.title = "修改测评因子信息（维度）";
        // console.log("要修改的表单",this.form)
      });

    },
    //获得因子分计算公式的formulaId 
    handleFormulaId(selectedValue) {
      const selectedFormula = this.formulaList.find(item => item.formulaName === selectedValue);
      if (selectedFormula) {
        const formulaId = selectedFormula.formulaId;
        this.queryParams.formulaId = formulaId
        this.form.formulaId = formulaId
      }
    },
    //为得到scaleId的回调函数
    handleScaleId(selectedValue) {
      const selectedScale = this.scaleTitleList.find(item => item.scaleTitle === selectedValue);
      if (selectedScale) {
        const scaleId = selectedScale.scaleId;
        this.form.scaleId=scaleId
        this.queryParams.scaleId = scaleId
      }
    },
    /** 提交按钮 */
    submitForm() {
      console.log("form信息",this.form);
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.factorResult = this.factorResultList.map(item => {
            return `${item.ScoreScale1}!@#$${item.ScoreScale2}@#$%${item.Result}#$%^${item.Heart}`;
          }).join('$%^&');
          console.log("scoreResultList",this.scoreResultList);
          this.form.scoreResult = this.scoreResultList.map(item=>{
            return `${item.Score1}!@#$${item.Score2}@#$%${item.Sex}#$%^${item.Age1}%^&*${item.Age2}^&*(${item.Level}`;
          }).join('$%^&');
          console.log("form信息111",this.form);
          if (this.form.factorId != null) {
            updateFactor(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          } else {
            this.form.scaleFormula.formulaId = this.form.formulaId;
            this.form.scaleFormula.formulaName = this.form.formulaName;
            // console.log("传的表单",this.form);
            addFactor(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.reset();
              this.getList();
            });
          }
        }else{
          this.$message.error("请填写必要的字段");
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const factorIds = row.factorId || this.ids;
      this.$modal.confirm('是否确认删除测评因子信息编号为"' + factorIds + '"的数据项？').then(function() {
        return delFactor(factorIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/factor/export', {
        ...this.queryParams
      }, `factor_${new Date().getTime()}.xlsx`)
    },
    //清空查询框的因子分计算公式
     handleClear() {
      this.queryParams.formulaId = null;
    },
    
  }
};
</script>
<style scoped>

</style>    

<style>
.myTooltips{
  background-color: rgb(108, 195, 230)!important;
   color: #fff;
   border: 1px solid #333;
   max-width: 30%;
   text-indent:2em;
}

</style>